import { login, logout, getInfo } from '@/api/account'
import { setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    _id: '',
    username: '',
    avatar: '',
    role: '',
    powers: '',
    status: true,
    mobile: '',
    mail: ''
  },

  mutations: {
    SET_USER: (state, obj) => {
      if (obj) {
        Object.assign(state, obj)
      } else {
        state = {}
      }
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(res => {
          const data = res.data
          setToken(res.token)
          commit('SET_USER', data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          commit('SET_USER', data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_USER', null)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_USER', null)
        removeToken()
        resolve()
      })
    }
  }
}

export default user
